import pymysql
from Mapper.user_title_mapper import UserTitleMapper, UserTitleMapping

"""用户职称业务实现类"""
class UserTitleImpl:
    def __init__(self, db_config):
        self.db_config = db_config
        self.connection = None
        self.cursor = None

    """使用上下文管理器管理数据库连接"""
    def __enter__(self):
        self.connection = pymysql.connect(**self.db_config)
        self.cursor = self.connection.cursor()
        return self

    """关闭数据库连接"""
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.commit()
            self.connection.close()

    """插入用户职称映射记录"""
    def insert_user_title(self, user_title):
        mapper = UserTitleMapper(self.cursor)
        return mapper.insert(user_title)

    """根据用户ID和业务类型删除记录"""
    def delete_user_title_by_user_id_and_business_type(self, user_id, business_type):
        mapper = UserTitleMapper(self.cursor)
        return mapper.delete_by_user_id_and_business_type(user_id, business_type)

    """根据用户ID获取所有职称"""
    def get_titles_by_user_id(self, user_id):
        mapper = UserTitleMapper(self.cursor)
        return mapper.get_titles_by_user_id(user_id)

    """根据用户ID和业务类型获取职称"""
    def get_user_business_titles(self, user_id, business_type):
        mapper = UserTitleMapper(self.cursor)
        return mapper.get_user_business_titles(user_id, business_type)